<!-- 藏品工单管理 -->
<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NInput,
  NSelect,
  NSpace,
  NModal,
  // NTooltip,
  // type SelectOption,
  type DataTableColumns,
  NDatePicker
} from 'naive-ui'
import { h, ref, reactive, watch, type VNode, onMounted,onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
const message = useMessage()
const route = useRoute()
const form = reactive({
  key: null,
  orderTypeCode: null, //征集方式
  statusCode: null, //编目状态
  datetime: null
})
const backId = ref()
// const renderOption = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
//   h(NTooltip, null, {
//     trigger: () => node,
//     default: () => option.label
//   })
// )
const rowKey: any = (e: any) => e.subItemCode || ''
const columns: DataTableColumns = [
  // {
  //   type: 'selection',
  //   width: '1rem'
  // },
  {
    title: '编号',
    key: 'orderNumber',
    width: '8rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '发起人',
    key: 'createdBy',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '发起类型',
    key: 'orderTypeName',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '日期',
    key: 'createdTime',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    },
    render: (e: any) => {
      return e?.createdTime
    }
  },
  {
    title: '状态',
    key: 'statusName',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => {
      let actions = [
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => {
              router.push({
                path: '/collection/process/pillManage/detail',
                query: { id: e.id, redirect: router.currentRoute.value.fullPath } //2编目 1初编
              })
            }
          },
          {
            default: () => '详情'
          }
        )
        //飞飞：隐藏
        // h(
        //   NButton,
        //   {
        //     type: 'primary',
        //     quaternary: true,
        //     color: '#FD4A29',
        //     style:{
        //       display:e?.statusName=='通过'?'none':'inline'
        //     },
        //     onClick: () => handleReback(e, true)
        //   },
        //   {
        //     default: () => '删除'
        //   }
        // )
      ]
      // 出库单&审批通过
      if (e.orderTypeCode == 'A3501' && e.statusCode == 'A0605') {
        actions.push(
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              style: {
                marginLeft: '5px'
              },
              onClick: async () => {
                debugger
                // 清空工单
                await batchDeleteOrder()
                // 批量加入工单
                await batchInOrder(e)
                router.push({
                  path: '/collection/process/ManageProcess/submitFile',
                  query: { type: 1, redirect: router.currentRoute.value.fullPath, isReturn: 1 } //1 藏品管理 2 工单
                })
              }
            },
            {
              default: () => '快速回库'
            }
          )
        )
      }
      return actions
    }
  }
]
const reset = () => {
  form.datetime = null
  form.key = null
  form.statusCode = null
  form.orderTypeCode = null
}
//筛选条件
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    queryTableData(true)
  }
})
const piciList = ref()
// 批次下拉
const piciFn = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getPullMenusOption'
  })
  if (error) return message.error(error.message)
  piciList.value = res?.data?.map((it: any) => {
    return { value: it.id, label: it.name }
  })
}
// 工单独有下拉
const codeFnPill = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCodeOfOrder',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data
    .filter((m: any) => m.dicName != '草稿' && m.dicName != '撤销')
    ?.map((it: any) => {
      return { value: it.dicCode, label: it.dicName }
    })
}
// 字典下拉
const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data
    .filter((m: any) => m.dicName != '草稿' && m.dicName != '撤销')
    ?.map((it: any) => {
      return { value: it.dicCode, label: it.dicName }
    })
}
const collectFactionList: any = ref()
const statusList: any = ref()
const modalVisible = ref(false)
// 点击退回
const againBack = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'deleteOrder',
    override: {
      data: {
        id: backId.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  queryTableData()
}

//点击删除
const handleReback = (val: any, type: any) => {
  modalVisible.value = true
  console.log(val)
  if (!type) backId.value = null
  else {
    backId.value = val.id
  }
}

//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const notIssuedId = ref()
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
function selectionChangeHandle(val: any, info: any) {
  dataListSelections.value = val
  notIssuedId.value = []
  info.map((i: any) => {
    if (i.distributionStatus == '0') {
      notIssuedId.value.push(i.id)
    }
  })
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref()
const queryTableDataBefore = () => {
  queryTableData(true)
  //  暂未使用
  // if (
  //   form.itemTypeCode ||
  //   form.key ||
  //   form.statusCode ||
  //   form.orderTypeCode
  // ) {
  //   queryTableData()
  // } else {
  //   message.info('请输入查询条件')
  // }
}
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  dataListSelections.value = []
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectingOrderlistPageList',
    override: {
      params: {
        key: form.key,
        orderTypeCode: form.orderTypeCode,
        statusCode: form.statusCode,
        startDate: form.datetime?.[0],
        endDate: form.datetime?.[1],
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  if (error) return message.error(error.message)
  const tmp: any = res.data
  tableData.value = tmp?.list
  paginationReactive.itemCount = tmp.totalCount
  console.log(paginationReactive.itemCount)
  tableLoading.value = false
}
/** 清空工单 */
const batchDeleteOrder = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'batchDelete'
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
}
// 批量加入工单
const batchInOrder = async (e: any) => {
  // 获取出库单工单详情藏品
  sendRequest({
    module: 'collectProcess',
    api: 'listItemsPage',
    override: {
      params: {
        limit: 9999,
        page: 1,
        orderId: e.id
      }
    }
  }).then(async ([err, res]) => {
    console.log('res: ', res)
    if (err) return
    const [error, resolve] = await sendRequest({
      module: 'collectProcess',
      api: 'collectingItemUserOrderTemporarySave',
      override: {
        data: {
          subItemCodeList: res.data.list?.map((item: { subItemCode: any }) => item.subItemCode)
        }
      }
    })
    if (error) return message.error(error.message)
    if (resolve.code !== 0) return message.error(res.msg)
  })
}
const keyUpDown = (e: any) => e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route.path,
  () => {
    if (route.path == '/collection/process/pillManage/index')
    {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
onMounted(() => {
  piciFn()
  codeFn('A06', statusList) //状态,关联字典A06
  codeFnPill('A35', collectFactionList) //发起类型,关联字典A35
  queryTableData()
})
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="编号:">
            <NInput
              placeholder="请输入编号"
              v-model:value="form.key"
            />
          </NFormItem>
          <NFormItem label="发起类型:">
            <NSelect
              :options="collectFactionList"
              v-model:value="form.orderTypeCode"
              placeholder="请选择发起类型"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="状态:">
            <NSelect
              :options="statusList"
              v-model:value="form.statusCode"
              placeholder="请选择状态"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="日期:">
            <NDatePicker
              input-readonly
              v-model:formatted-value="form.datetime"
              value-format="yyyy-MM-dd"
              type="daterange"
              clearable
              style="width: 300rem"
              placeholder="请选择日期"
            />
          </NFormItem>
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px"
              ghost
              @click="queryTableDataBefore()"
            >
              查询
            </NButton>
          </NFormItem>
          <NFormItem>
            <NButton
              style="width: 78px; margin-right: 10px"
              ghost
              type="primary"
              @click="reset()"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <!-- 暂时隐藏 -->
          <!-- <NButton
            color="#5FB17F"
            @click="
              () =>
                router.push({
                  path: '/collection/process/pillManage/submitFile',
                  query: {} //2编目 1初编
                })
            "
          >
            申请工单
          </NButton> -->
          <!-- <NButton
            color="#5FB17F"
            ghost
            @click="handleReback(1, false)"
            :disabled="dataListSelections.length ? false : true"
          >
            批量退回
          </NButton> -->
          <!-- <NButton
            color="#5FB17F"
            ghost
            @click="
              () =>
                router.push({
                  path: '/collection/process/pillManage/submitFile',
                  query: {} //2编目 1初编
                })
            "
          >
            申请工单
          </NButton> -->
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        :scroll-x="1000"
        :loading="tableLoading"
        :checked-row-keys="dataListSelections"
        @update:checked-row-keys="selectionChangeHandle"
      />
    </template>

    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againBack"
      title="警告"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        是否删除当前审批单？
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
